package com.mj.controller;

import com.mj.dao.BookDao;
import com.mj.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class BookController {
    @Autowired
    protected BookDao bookDao;

    @RequestMapping("/show")
    @ResponseBody
    public void show() {
        System.out.println(bookDao.queryById(4));
    }

    @RequestMapping("/shows")
    public String shows(Model model) {
        model.addAttribute("book", bookDao.queryById(4));
        return "show";
    }

    @RequestMapping("")
    public String index(Model model) {
        model.addAttribute("books", bookDao.queryAll());
        return "index";
    }

    @RequestMapping("/addbook")
    public String addbook() {
        return "bookadd";
    }

    @RequestMapping(value = "/addbooks",method = RequestMethod.POST)
    public String addb(String name, double price,String date) throws ParseException {//由于输入的是字符串，所以在接收的时候需要转换为字符串，用String接受
        Book book = new Book();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//定义需要转字符串的格式
        Date dat = sdf.parse(date);//将需要转换的字符串进行转换相应格式的日期
        book.setName(name);
        book.setPrice(price);
        book.setDate(dat);
        bookDao.insert(book);
        //return "sssss";
        //bookDao.add(name,price,new Date());
        return "redirect:/";
    }
    //@RequestMapping(value = "/delbook",method = RequestMethod.GET)这是普通id传过来模式
    @RequestMapping(value = "/delbook/{id}",method = RequestMethod.GET)
    //public String dele(int id){普通id模式
    public String dele(@PathVariable("id") int id){
        bookDao.deleteById(id);
        return "redirect:/";
    }
}
